package com.xhu.water_supply.utils;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Description 拼音工具类
 * @Date 2019-09-23 09:31
 * @Author Liujx
 * Version 1.0
 **/
public class PinyinUtils {

    static Logger log = LoggerFactory.getLogger(PinyinUtils.class);

    /**
     * 获取汉字串拼音首字母，英文字符不变
     * @param c 汉字
     * @return 汉语拼音首字母
     */
    public static Character getFirstSpell(char c) {
        Character result = null;
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        if (c > 128) {
            try {
                String[] temp = PinyinHelper.toHanyuPinyinStringArray(c, defaultFormat);
                if (temp != null) {
                    result =  temp[0].charAt(0);
                }
            } catch (BadHanyuPinyinOutputFormatCombination e) {
                log.error("汉语字符获取首字母失败,字符：{}，错误信息：{}", c, e);
                e.printStackTrace();
            }
        }else{
            result = c;
        }
        return result;
    }
}
